/*
 * ID.java
 *
 * Created on August 21, 2007, 1:42 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.xeerkat.xmpp;

/**
 *
 * @author alex
 */
public class ID implements Comparable<ID>
{
   
   String name;
   String domain;
   String resource;
   String password;
   
   /** Creates a new instance of ID */
   public ID(String id)
   {
      int at = id.indexOf('@');
      if (at<0) {
         name = null;
         domain = id;
         resource = null;
         return;
      } else if (at==0) {
         throw new IllegalArgumentException("The username in the XMPP id "+id+" is missing.");
      }
      name = id.substring(0,at);
      domain = id.substring(at+1);
      if (domain.length()==0) {
         throw new IllegalArgumentException("The domain in the XMPP id "+id+" is missing.");
      }
      int slash = domain.indexOf('/');
      if (slash>0) {
         resource = domain.substring(slash+1);
         domain = domain.substring(0,slash);
      } else {
         resource = null;
      }
   }
   
   /** Creates a new instance of ID */
   public ID(String name,String domain,String resource)
   {
      this.name = name;
      this.domain = domain;
      this.resource = resource;
      this.password = null;
   }

   public ID(String name,String domain)
   {
      this(name,domain,null);
   }
   
   public String getName() {
      return name;
   }
   
   public String getDomain() {
      return domain;
   }
   
   public String getResource() {
      return resource;
   }
   
   public void setPassword(String password)
   {
      this.password = password;
   }
   
   public void setResource(String resource)
   {
      this.resource = resource;
   }
   
   public String getPassword() {
      return password;
   }

   @Deprecated
   public String toXMPPId() {
      return name==null ? domain : name+"@"+domain;
   }
   public String toString() {
      return resource==null ? (name==null ? domain : name+"@"+domain) : name+"@"+domain+"/"+resource;
   }
   
   public String toURIEncodedString() {
      return resource==null ? (name==null ? domain : name+"%40"+domain) : name+"%40"+domain+"/"+resource;
   }

   public String toAuthority() {
      return name==null ? domain : name+"@"+domain;
   }

   public boolean isSameAuthority(ID other) {
      return name==null ? domain.equals(other.getDomain()) : name.equals(other.getName()) && domain.equals(other.getDomain());
   }
   
   public boolean equals(Object other) {
      if (other instanceof ID) {
         return ((ID)other).compareTo(this)==0;
      } else {
         return false;
      }
   }
   
   public int compareTo(ID other) {
      return toString().compareTo(other.toString());
   }
   
}
